package com.my.middleware;

import com.my.resquest.NettyHttpRequest;
import com.my.trie.FilterTreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WangLuoXin
 * &#064;Date 2024/9/14  09:45
 **/
public class MiddlewareActuator {

    private final List<BeforeFilter> beforeFilters = new ArrayList<>();

    private final FilterTreeNode include = new FilterTreeNode("/", new ArrayList<>());

    private final FilterTreeNode exclude = new FilterTreeNode("/", new ArrayList<>());

    public void useBefore(BeforeFilter beforeFilter) {
        for (String path : beforeFilter.includePath()) {
            include.putPath(path);
        }
        for (String path : beforeFilter.excludePath()) {
            exclude.putPath(path);
        }
        beforeFilters.add(beforeFilter);
    }

    public void execBefore(NettyHttpRequest request) {
        beforeFilters.forEach(beforeFilter -> {
            if (isExec(request.getRequest().uri())) {
                beforeFilter.before(request);
            }
        });
    }

    /**
     * 判断当前 url是否可执行
     * @param url  请求路径
     * @return true 可以执行  false  不可执行
     */
    private Boolean isExec(String url) {
        Boolean includeFlag = include.getPath(url);
        if (includeFlag) {
            return !exclude.getPath(url);
        }
        return Boolean.TRUE;
    }

}
